package com.pilipala.interceptor;

import com.pilipala.constant.JwtConstant;
import com.pilipala.context.BaseContext;
import com.pilipala.properties.JwtProperty;
import com.pilipala.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

//拦截jwt
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtProperty jwtProperty;
    /**
     * 拦截器业务
     * @param request 请求
     * @param response 响应
     * @param handler 上一个的拦截器
     * @return 返回真假值
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) {
        if (!(handler instanceof HandlerMethod)){
//          拦截到的不是动态方法  -----   比如静态资源  直接放行
            return true;
        }
//        获取token
        String token =request.getHeader(JwtConstant.TOKEN_NAME);
        log.info(token);
//        要除掉token前面的"Bearer "
        token = token.substring(7);
        log.info(token);
        if (jwtUtil.validateToken(jwtProperty.getSecretKey(),token)) {
//            如果token合法
            Claims claims = jwtUtil.parseToken(jwtProperty.getSecretKey(), token);
//            获取到用户Id
            Long id = Long.valueOf(claims.get(JwtConstant.USER_ID).toString());
            log.info(id.toString());
//            设置到上下文
            BaseContext.setCurrentId(id);
            return true;
        }
        return false;
    }
}
